import React, { Component } from 'react';
import { Modal, Button, Steps, Spin, Form, Input, message, Icon } from 'antd';
import { deepCopy, messages } from 'share/common';
import Chooser from 'components/chooser';
import { connect } from 'react-redux';
import 'styles/components/template/role-config/role-config.scss';
import roleConfigService from 'components/template/role-config/role-config.service';
import LoginService from 'containers/login/login.service';
import menuRoute from 'routes/menuRoute';

const confirm = Modal.confirm;

class RoleConfig extends Component {
  constructor(props) {
    super(props);
    this.state = {
      config: {},
      visible: false,
      isPhoneRight: true,
      isCodeRight: true,
      phone: '',
      code: '',
      current: 0,
      spinning: true,
      PopConfirm: false,
      verifiedCodeLoad: false,
      targetTime: 0,
      btnLoading: false,
      updateCount: 0,
      codeLoading: false,
      haveSendCodeAlready: false,
      isReadOnly: false
    };
    this.firstLoading = true;
    this.isFromGuide = false;
  }

  componentDidMount() {
    const { onRef } = this.props;
    onRef && onRef(this);
    this.getConfig();
  }

  setRoleConfig = (value, isFromGuide, isReadOnly) => {
    this.isFromGuide = isFromGuide;
    if (value) {
      this.setState({ visible: true, isReadOnly });
      this.getConfig();
    } else {
      this.setState({ visible: false, isReadOnly });
    }
  };

  // 获取配置情况
  getConfig = () => {
    roleConfigService.getConfig().then((res) => {
      this.firstLoading = false;
      if (res.status === 200) {
        let current;
        const copyData = deepCopy(res.data);
        const superAdmin = copyData.superAdmin;
        const superFinance = copyData.superFinance;
        copyData.superAdmin = superAdmin.map((item) => {
          return { id: item.grantValue, fullName: item.userName };
        });
        copyData.superFinance = superFinance.map((item) => {
          return { id: item.grantValue, fullName: item.userName };
        });
        if (res.data.superAdmin.length > 0 && res.data.superFinance.length > 0) {
          current = 2;
        } else if (res.data.superAdmin && res.data.superAdmin.length > 0) {
          current = 1;
        } else {
          current = 0;
        }
        this.setState({ config: copyData, current, spinning: false });
      }
    });
  };

  // 判断是否完成配置
  getFinishStatus = () => {
    const { config } = this.state;
    const isFinish = !(config.superAdmin && config.superAdmin.length && config.superFinance.length);
    return isFinish;
  };

  // 点击右上角X
  onCancel = () => {
    const { config, isReadOnly } = this.state;
    const isFinish = this.getFinishStatus();
    if ((!isFinish && config.mobile) || isReadOnly) {
      window.localStorage.setItem('hly.role-config', 'false');
      this.setState({ visible: false }, () => {
        this.props.onFinish(this.isFromGuide, true);
        this.isFromGuide = false;
      });
    } else {
      confirm({
        title: messages('common-1.key490') /* 您还有未完成的配置项，可能导致报销流程无法正常完成，是否确定要关闭？*/,
        okText: messages('common-1.key41') /* 关闭*/,
        iconType: 'exclamation-circle',
        cancelText: messages('common-1.key491') /* 继续配置*/,
        onOk: () => {
          window.localStorage.setItem('hly.role-config', 'false');
          this.setState({ PopConfirm: false, visible: false }, () => {
            this.props.onFinish(this.isFromGuide, false);
            this.isFromGuide = false;
          });
        }
      });
    }
  };

  // 配置 超级管理员
  handleAdminChange = (data) => {
    const { user } = this.props;
    if (data.length !== 0) {
      let validate = false;
      data.forEach((item) => {
        if (item.id === user.id) {
          validate = true;
        }
      });
      if (validate) {
        this.setState({ spinning: true });
        roleConfigService
          .updateConfig(
            'superAdmin',
            data.map((item) => item.id)
          )
          .then((res) => {
            if (res.status === 200) {
              this.getConfig();
              message.success(messages('common.save.success', { arg1: '' }) /* {arg1} 保存成功*/);
            }
          })
          .catch((err) => {
            this.getConfig();
          });
      } else {
        message.error(messages('common-1.key492') /* 不可以取消当前操作人*/);
      }
    } else {
      message.error(messages('common-1.key493') /* 至少选择一个人员*/);
    }
  };

  // 配置 财务管理员
  handleFinanceChange = (data) => {
    if (data.length !== 0) {
      this.setState({ spinning: true });
      roleConfigService
        .updateConfig(
          'superFinance',
          data.map((item) => item.id)
        )
        .then((res) => {
          if (res.status === 200) {
            this.getConfig();
            message.success(messages('common.save.success', { arg1: '' }) /* {arg1} 保存成功*/);
          }
        })
        .catch((err) => {
          this.getConfig();
        });
    } else {
      message.error(messages('common-1.key493') /* 至少选择一个人员*/);
    }
  };

  // 点击完成 （绑定手机号）
  handleFinish = () => {
    const { config } = this.state;
    window.localStorage.setItem('hly.role-config', 'false');
    this.setState({ visible: false }, () => {
      this.props.onFinish(this.isFromGuide, true);
      this.isFromGuide = false;
    });
  };

  goToRoleAuthorize = () => {
    window.open((window.ISIE9 ? '#' : '') + menuRoute.getRouteItem('role-permission-setting', 'key').url, '_blank');
  };

  render() {
    const { visible, config, spinning, isReadOnly } = this.state;
    const isFinish = this.getFinishStatus();
    return (
      <div className="role-config">
        <Modal
          width={760}
          maskClosable={false}
          title={messages('common-1.key494') /* 角色授权*/}
          visible={visible}
          bodyStyle={{ padding: 0 }}
          className="role-config-modal"
          onCancel={this.onCancel}
          onOk={this.handleFinish}
        >
          <Spin spinning={spinning}>
            <div className="container-box">
              <div className="title-box">
                <div className="text">
                  {messages('common-1.key495') /* 如需设置和修改更多内容，请前往：用户与权限-角色管理-*/}
                  <span className="a-link" onClick={this.goToRoleAuthorize}>
                    {messages('common-1.key494') /* 角色授权*/}
                  </span>
                </div>
              </div>
              <div className="content-box">
                <Form className="new-form">
                  <Form.Item label={messages('common-1.key496') /* 超级管理员*/} required>
                    <Chooser
                      type="user"
                      disabled={isReadOnly}
                      showClear={false}
                      value={config.superAdmin}
                      valueKey="id"
                      labelKey="fullName"
                      onChange={this.handleAdminChange}
                    />
                    <div className="item-tips">
                      {messages('common-1.key1310')/*拥有系统设置的管理权限，包含：角色授权、组织架构与费用维护等*/}
                    </div>
                  </Form.Item>
                  <Form.Item label={messages('common-1.key498') /* 财务管理员*/} required>
                    <Chooser
                      type="user"
                      disabled={isReadOnly}
                      showClear={false}
                      value={config.superFinance}
                      valueKey="id"
                      labelKey="fullName"
                      onChange={this.handleFinanceChange}
                    />
                    <div className="item-tips">
                      {messages('common-1.key499') /* 拥有系统财务管理权限，包括审核、付款、报表等*/}
                    </div>
                  </Form.Item>
                </Form>
              </div>
            </div>
          </Spin>
        </Modal>
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    user: state.login.user
  };
}

const wrappedRoleConfig = Form.create()(RoleConfig);
export default connect(mapStateToProps)(wrappedRoleConfig);
